#pragma once
#include <string>
#include <cstdbool>

#ifdef _WIN32
#include <direct.h>
#endif

#ifdef __linux__
#include <sys/stat.h>
#endif

#include <ctime>

namespace bit
{
    namespace util
    {
        // 以字符串的形式获取当前时间：
        static const std::string get_curtime()
        {
            char ret[64];
            time_t now = time(nullptr);

            struct tm *cur_time = localtime(&now);
            snprintf(ret, sizeof ret, "%d-%02d-%02d %02d:%02d:%02d",
                     cur_time->tm_year + 1900,
                     cur_time->tm_mon + 1,
                     cur_time->tm_mday,
                     cur_time->tm_hour,
                     cur_time->tm_min,
                     cur_time->tm_sec);
            return std::string(ret);
        }

        // 根据指定的文件路径判断某个文件是否存在:
        static bool exists(const std::string &path)
        {
            bool ret = true;
            struct stat tmp;
            if (stat(path.c_str(), &tmp) != 0)
            {
                ret = false;
            }
            return ret;
        }

        // 获取指定文件的所处的文件的路径:
        static const std::string get_path(const std::string path)
        {
            std::string ret;
            size_t pos = path.find_last_of("/\\");
            if (pos == std::string::npos)
            {
                ret = '.';
            }
            else
            {
                ret = path.substr(0, pos + 1);
            }
            return ret;
        }

        // 创建目录：假设path里面的文件名全是目录
        static void create_path(const std::string &path)
        {
            if (exists(path))
                return;
            size_t idx = 0, pos = 0;
            while (idx < path.size())
            {
                pos = path.find_first_of("/\\", idx);
                if (pos == std::string::npos)
                {
                    #ifdef _WIN32
                    int tmp = _mkdir(path.c_str());
                    #endif

                    #ifdef __linux__
                    int tmp = mkdir(path.c_str(), 0777);
                    #endif
                    if (tmp < 0)
                    {
                        std::cout << "警告：日志目录创建失败" << std::endl;
                    }
                    return;
                }
                std::string parent_path(path.substr(0, pos + 1));
                if (!exists(parent_path))
                {
                    #ifdef __linux__
                    int tmp = mkdir(parent_path.c_str(), 0777);
                    #endif

                    #ifdef _WIN32
                    int tmp = _mkdir(parent_path.c_str());
                    #endif
                    if (tmp < 0)
                    {
                        std::cout << "警告：日志目录创建失败" << std::endl;
                        return;
                    }
                }
                idx = pos + 1;
            }
        }
    }
}